package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import io.lettuce.core.dynamic.annotation.CommandNaming;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

@CommandNaming
@Topic(TopicConfig.VMS_STATUS_TOPIC)
public class VMStatusHandler implements MsgHandler {
    @Autowired
    private TaskService taskService;

    @Autowired
    private VMService vmService;

    @Override
    public void process(String jsonMsg) throws IOException {
        VmStatusContract vmStatusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        if (vmStatusContract == null || vmStatusContract.getStatusInfo() == null || vmStatusContract.getStatusInfo().size() <= 0) {
            //如果售货机为非正常状态  则创建维修工单
            if (vmStatusContract.getStatusInfo().stream().anyMatch(s -> s.isStatus() == false)) {
                //根据售货机编号  查询售货机信息
                VmVO vmInfo = vmService.getVMInfo(vmStatusContract.getInnerCode());
                //查询最少工单用户
                int userId = taskService.getLeastUser(vmInfo.getRegionId(), true);
                //创建工单对象
                TaskViewModel task = new TaskViewModel();
                task.setUserId(userId);
                task.setDesc("自动维修工单");
                task.setInnerCode(vmInfo.getInnerCode());//设置售货机编号
                task.setCreateType(0);//设置 创建类型为 自动工单
                //调用方法 创建
                taskService.create(task);

            }
            return;
        }


    }
}
